const { ipcMain, BrowserWindow } = require('electron')
const path = require('path')
const saveas = require('./saveas')

const cssText = `width: 100px; height: 30px; background: #ee742f; text-align: center; line-height: 30px; position: fixed; right: 20px; bottom: 60px; cursor: pointer; color: #fff;font-size:12px;`

const js = `
  const div = document.createElement('div')
  div.id = 'btn'
  div.innerHTML = '关闭窗口'
  div.style.cssText = '${cssText}'
  div.addEventListener('click', () => { exposeApi.closeWindow() })
  document.body.appendChild(div)
`

let win

ipcMain.on('on-openwin-event', (event, url) => {
  win = new BrowserWindow({
    width: 1100,
    height: 800,
    webPreferences: {
      preload: path.resolve(__dirname, '../preload.js')
    }
  })

  win.loadURL(url)

  // win.webContents.openDevTools()

  win.webContents.executeJavaScript(js)

  win.webContents.on('context-menu', async (event, args) => {
    saveas(args.srcURL)
  })
})

ipcMain.on('on-close-window', (event, url) => {
  win.close()
})